#include "ADS1115_IIC_H.h"
#include "esp_log.h"
#include "driver/i2c.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include <string.h>




void ADS1115_IIC_Delay(void)
{
    esp_rom_delay_us(10);  // 延迟 10 微秒
}



// 写一个字节到 I2C 设备
int ADS1115_IIC_WriteByte(uint8_t data) {
    i2c_cmd_handle_t cmd = i2c_cmd_link_create();
    i2c_master_write_byte(cmd, data, true);  // 发送字节
    return i2c_master_cmd_begin(I2C_MASTER_NUM, cmd, pdMS_TO_TICKS(1000));  // 执行命令
}

// 读取一个字节从 I2C 设备
int ADS1115_IIC_ReadByte(uint8_t *data) {
    i2c_cmd_handle_t cmd = i2c_cmd_link_create();
    uint8_t received_data = 0;
    i2c_master_read_byte(cmd, &received_data, I2C_MASTER_LAST_NACK);  // 读取字节
    *data = received_data;
    return i2c_master_cmd_begin(I2C_MASTER_NUM, cmd, pdMS_TO_TICKS(1000));  // 执行命令
}

// 写寄存器数据到 I2C 设备
int IIC_WriteReg(uint8_t i2c_addr, uint8_t reg_addr, uint8_t reg_dat)
{
    int ret;
    uint8_t data[2] = { reg_addr, reg_dat };

    // 使用 I2C 写操作
    ret = i2c_master_write_to_device(I2C_MASTER_NUM, i2c_addr, data, sizeof(data), pdMS_TO_TICKS(1000));
    
    return ret;
}

// 写寄存器地址到 I2C 设备
int IIC_Write_addr(uint8_t i2c_addr, uint8_t reg_addr)
{
    int ret;
    uint8_t data = reg_addr;

    // 使用 I2C 写操作
    ret = i2c_master_write_to_device(I2C_MASTER_NUM, i2c_addr, &data, sizeof(data), pdMS_TO_TICKS(1000));

    return ret;
}

// 写多个字节到 I2C 设备
int IIC_WriteBuf(uint8_t i2c_addr, uint8_t reg_addr, uint8_t *Pdat, uint8_t len)
{
    int ret;
    uint8_t *data = (uint8_t *)malloc(len + 1); // 分配内存，包含寄存器地址 + 数据长度
    if (data == NULL) {
        ESP_LOGE("I2C", "Memory allocation failed for IIC_WriteBuf.");
        return ESP_ERR_NO_MEM;
    }

    // 先写寄存器地址，再写数据
    data[0] = reg_addr;
    memcpy(&data[1], Pdat, len); // 将数据复制到缓冲区

    ret = i2c_master_write_to_device(I2C_MASTER_NUM, i2c_addr, data, len + 1, pdMS_TO_TICKS(1000));

    free(data); // 释放内存

    return ret;
}

// 读取多个字节从 I2C 设备
int IIC_ReadData(uint8_t i2c_addr, uint8_t reg_addr, uint8_t *pdat, uint8_t len)
{
    int ret;
    
    // 首先发送寄存器地址
    ret = i2c_master_write_to_device(I2C_MASTER_NUM, i2c_addr, &reg_addr, 1, pdMS_TO_TICKS(1000));
    if (ret != ESP_OK) {
        return ret;
    }

    // 读取数据
    ret = i2c_master_read_from_device(I2C_MASTER_NUM, i2c_addr, pdat, len, pdMS_TO_TICKS(1000));

    return ret;
}

// 读取ADS1115寄存器
int16_t ADS1115_ReadAdsReg(uint8_t i2cAddress, uint8_t reg)
{
    uint8_t buf[2] = {0};
    
    // 读取数据
    IIC_ReadData(i2cAddress, reg, buf, sizeof(buf));
    
    // 将读取的2字节数据合并为16位
    return (buf[0] << 8) | buf[1];
}

// 写入ADS1115寄存器
void ADS1115_WriteAdsReg(uint8_t i2cAddress, uint8_t reg, uint16_t value)
{
    uint8_t buffer[2] = {0};
    
    // 将16位数据分成高位和低位
    buffer[0] = (value >> 8); 
    buffer[1] = value & 0xFF;
    
    // 写入数据
    IIC_WriteBuf(i2cAddress, reg, buffer, 2);
}